<template>
  <a-modal
    :title="title"
    :visible="visible"
    :width="800"
    :confirm-loading="loading"
    @ok="() => { $emit('ok', model) }"
    @cancel="() => { $emit('cancel', model) }"
    cancelText="取消"
    okText="保存"
    :destroyOnClose="true"
  >
    <k-form-build
      ref="kfb"
      :defaultValue="defaultValue"
      :value="jsonData"
      @submit="handleSubmit"
      @change="handleChange"
    />
    <!--<div class="table-operator">
      <a-button type="primary" @click="handleGetData">获取数据</a-button>
      <a-button type="primary" @click="handleUpdate">修改数据</a-button>
      <a-button type="primary" @click="handleReset">重置表单</a-button>
    </div>-->
  </a-modal>
</template>

<script>
  export default {
    name: 'AddRows',
    props: {
      visible: {
        type: Boolean,
        required: true
      },
      loading: {
        type: Boolean,
        default: () => false
      },
      model: {
        type: Object,
        default: () => null
      },
      title: {
        type: String,
        default: () => ''
      }
    },
    data () {
      return {
        defaultValue: {
          select_1585829530472: "2",
          radio_1585829530935: "3"
        },
        jsonData: null,
      }
    },
    methods: {
      handleChange (value, key) {
        // 数据变化时触发
        // console.log(value, key);
      },
      handleSubmit (p) {
        // 通过表单提交按钮触发，获取promise对象
        p()
          .then(res => {
            // 获取数据成功
            alert(JSON.stringify(res));
          })
          .catch(err => {
            console.log(err, "校验失败");
          });
      },
      handleGetData () {
        // 使用getData函数获取数据
        return this.$refs.kfb.getData()
      },
      handleUpdate (data) {
        // 使用k-form-design组件的form属性修改表单数据
        this.defaultValue = data || this.defaultValue
        this.$refs.kfb && this.$refs.kfb.setData(this.defaultValue);
      },
      handleReset () {
        // 重置表单
        this.$refs.kfb && this.$refs.kfb.reset();
      }
    },
    created () {
      // 防止表单未注册
      // fields.forEach(v => this.form.getFieldDecorator(v))

      // 当 model 发生改变时，为表单设置值
      this.$watch('model', () => {
        if (this.model && this.model.config) {
          if (!this.jsonData) {
            this.jsonData = JSON.parse(this.model.config)
          }
          // 设置默认值
          this.defaultValue = this.model.data
        } else {
          this.jsonData = []
        }
      }, {
        deep: true
      })
    }
  }
</script>

<style scoped>

</style>
